<?php


namespace App\Http\Controllers\android\service;


use App\Http\Controllers\android\model\AdminSnModel;
use App\Http\Controllers\android\model\AppInstallModel;
use App\Http\Controllers\android\model\AppLogModel;
use App\Http\Controllers\android\model\AppUpdateModel;
use App\Http\Controllers\android\model\BrandModel;
use App\Http\Controllers\android\model\ClassifyModel;
use App\Http\Controllers\android\model\GradeModel;
use App\Http\Controllers\android\model\ParentAppModel;
use App\Http\Controllers\android\model\ParentSnModel;
use App\Http\Controllers\android\model\StatisticsAppModel;
use App\Http\Controllers\android\model\SysAppModel;
use App\Http\Controllers\android\model\TeacherAppModel;
use App\Http\Controllers\android\model\TeacherSnModel;
use App\Http\Controllers\android\model\TopicModel;
use App\Http\Controllers\android\validate\App;
use App\Http\Controllers\utils\ToolUtil;
use Illuminate\Support\Facades\DB;

class AppService
{

    /**
     * 获取所有应用和安装白名单应用
     * @param $param
     * @return false|string
     */
    public static function getAppAndWhite($param){

        $sn = ToolUtil::filterStr($param['sn']);
        $where = [];
        $parentSn = ParentSnModel::queryLeftAdminSn(['a.value'=>$sn],['p.id','teacher_id','a.is_lock']);
        if(empty($parentSn)){
            return ToolUtil::returnJson(-200,'该设备没有绑定');
        }

        if($parentSn['is_lock'] === 0){
            return ToolUtil::returnJson(400,'没有数据');
        }

        $data = [];
        $field = "a.app_package";
        if($parentSn['teacher_id']){

            $teacherSn = TeacherSnModel::queryLeftAdminSn(['a.value'=>$sn],['b.id']);
            if($teacherSn){
                $batch = $teacherSn['id'];
                $where[count($where)+1] = " find_in_set('{$batch}',a.bind_batch_id) ";
                $str = ' where '.implode('and',$where);
                $data = DB::select("select $field from t_teacher_app as a $str");
                $white_app = DB::table('t_white_app')->whereRaw(" find_in_set('{$batch}',batch_id) ")->first(['package_name']);
                if(!empty($white_app['package_name'])){
                    $package = explode(',',$white_app['package_name']);
                    foreach ($package as $key => $value) {
                        $data[]['app_package'] = $value;
                    }
                }
            }

        }else{

            $where[count($where)+1] = " a.sn_value='$sn' ";
            $str = ' where '.implode('and',$where);
            $data = DB::select("select $field from t_parent_app as a $str");
            $white_app = DB::table('t_white_app')->where('sn',$sn)->first(['package_name']);
            if(!empty($white_app['package_name'])){
                $package = explode(',',$white_app['package_name']);
                foreach ($package as $key => $value) {
                    $data[]['app_package'] = $value;
                }
            }

        }

        if(count($data)){
            return ToolUtil::returnJson(200,'成功',$data);
        }
        return ToolUtil::returnJson(400,'没有数据');
    
    }


    /**
     * 获取广告品牌信息
     * @param $param
     * @return false|string
     */
    public static function getBrand($param){
        $parentSn = ParentSnModel::queryLeftInfo(['a.value'=>$param['sn']],['g.class_name']);
        if(!$parentSn){
            return ToolUtil::returnJson(-200,'该设备还没有进行绑定');
        }
        $gradeId = self::handleClass($parentSn);
        if(empty($gradeId)){
            return ToolUtil::returnJson(400,'没有该信息');
        }
        $brand = BrandModel::queryLikeGet(['field'=>'grade_id','grade_id'=>$gradeId],['img_url']);
        if($brand){
            return ToolUtil::returnJson(200,'成功',$brand);
        }
        return ToolUtil::returnJson(400,'没有数据');
    }

    /**
     * 处理班级信息
     * @param $parentSn
     * @return mixed|string|null
     */
    public static function handleClass($parentSn){
        $preschool = ['大班','中班','小班'];
        $primarySchool = ['一年级','二年级','三年级','四年级','五年级','六年级'];
        $jMiddleSchool = ['初一','初二','初三'];
        $highSchool = ['高一','高二','高三'];
        $university = ['大一','大二','大三','大四'];
        if(in_array($parentSn['class_name'],$preschool)){
            $gradeId = GradeModel::queryValue(['title'=>'学前班'],'id');
        }elseif(in_array($parentSn['class_name'],$primarySchool)){
            $gradeId = GradeModel::queryValue(['title'=>'小学'],'id');
        }elseif(in_array($parentSn['class_name'],$jMiddleSchool)){
            $gradeId = GradeModel::queryValue(['title'=>'中学'],'id');
        }elseif(in_array($parentSn['class_name'],$highSchool)){
            $gradeId = GradeModel::queryValue(['title'=>'中学'],'id');
        }elseif(in_array($parentSn['class_name'],$university)){
            $gradeId = GradeModel::queryValue(['title'=>'大学'],'id');
        }else{
            $gradeId = '';
        }
        return $gradeId;
    }

    /**
     * 获取广告专题信息
     * @param $param
     * @return false|string
     */
    public static function getTopic($param){
        $parentSn = ParentSnModel::queryLeftInfo(['a.value'=>$param['sn']],['g.class_name']);
        if(!$parentSn){
            return ToolUtil::returnJson(-200,'该设备还没有进行绑定');
        }
        $gradeId = self::handleClass($parentSn);
        if(empty($gradeId)){
            return ToolUtil::returnJson(400,'没有该信息');
        }
        $topic = TopicModel::queryLikeGet(['field'=>'grade_id','grade_id'=>$gradeId],['img_url']);
        if($topic){
            return ToolUtil::returnJson(200,'成功',$topic);
        }
        return ToolUtil::returnJson(400,'没有数据');
    }

    /**
     * 获取应用分类信息
     * @param $param
     * @return false|string
     */
    public static function getClassify($param){
        $parentSn = ParentSnModel::queryLeftInfo(['a.value'=>$param['sn']],['g.class_name']);
        if(!$parentSn){
            return ToolUtil::returnJson(-200,'该设备还没有进行绑定');
        }
        $gradeId = self::handleClass($parentSn);
        if(empty($gradeId)){
            return ToolUtil::returnJson(400,'没有该信息');
        }
        $classify = ClassifyModel::queryLikeGet(['field'=>'grade_id','grade_id'=>$gradeId],['img_url']);
        if($classify){
            return ToolUtil::returnJson(200,'成功',$classify);
        }
        return ToolUtil::returnJson(400,'没有数据');
    }

    /**
     * 获取强制安装app信息
     * @param $param
     * @return false|string
     */
    public static function getForceDownload($param){
        $parentSn = ParentSnModel::queryLeftAdminSn(['a.value'=>$param['sn']],['p.teacher_id','p.id','a.is_lock']);
        $field = ['t.app_name','t.app_package','t.app_version_code','t.app_size','t.app_url','t.app_img','t.app_md5'];
        if(empty($parentSn)){
            return ToolUtil::returnJson(-200,'该设备还没有进行绑定');
        }

        if($parentSn['is_lock'] === 0){
            return ToolUtil::returnJson(400,'没有数据');
        }

        $bind = DB::table('t_bind_sn')->where('sn_value',$param['sn'])->first(['status']);
        if($bind['status'] !== 1){
            return ToolUtil::returnJson(-200,'该设备还没有进行绑定');
        }

        if(empty($parentSn['teacher_id'])){
            $data = DB::table('t_parent_app as t')
                ->where(['t.sn_value'=>$param['sn'],'t.is_silent'=>1])
                ->get($field);
        }else{
            $teacher = TeacherSnModel::queryLeftAdminSn(['a.value'=>$param['sn']],['b.id']);
            if($teacher){
                $data = DB::table('t_teacher_app as t')
                    ->where("bind_batch_id",'like','%'.$teacher['id'].'%')
                    ->where(['t.is_silent'=>1])
                    ->get($field);
            }else{
                $data = null;
            }
        }
        if(count($data)){
            return ToolUtil::returnJson(200,'成功',$data);
        }
        return ToolUtil::returnJson(400,'没有数据');
    }

    /**
     * 正在运行的应用
     * @param $param
     * @return false|string
     */
    public static function runNewApp($param){
        $sysApp = DB::table('t_sys_app')->get(['app_package']);
        $app = json_decode($param['app'],true);
        $parent = DB::table('t_parent_sn as p')
            ->leftJoin('t_admin_sn as a','p.admin_sn_id','=','a.id')
            ->where('a.value',$param['sn'])->first(['a.id','p.id as pId','p.teacher_id']);
        if(empty($parent)){
            return ToolUtil::returnJson(-200,'不存在该设备');
        }
        if(empty($parent['pId'])){
            return ToolUtil::returnJson(-200,'该设备没有绑定');
        }
        $data = [];
        if(count($sysApp)){
            foreach ($sysApp as $key=>$value){
                $data[$key] = $value['app_package'];
            }
        }
        
        if(in_array($app['app_package'],$data)){
            $appId = DB::table('t_sys_app')->where('app_package',$app['app_package'])->value('id');
            $type = 1;
        }elseif($parent['teacher_id']){
            $appId = DB::table('t_teacher_app')
                ->where(['app_package'=>$app['app_package'],'app_version_name'=>$app['version_name']])->value('id');
            $type = 2;
        }else{
            $appId = DB::table('t_parent_app')
                ->where(['app_package'=>$app['app_package'],'app_version_name'=>$app['version_name']])->value('id');
            $type = 3;
        }

        if(empty($appId)){
            return ToolUtil::returnJson(-200,'数据库找不到这个APP');
        }

        $minute = $app['start_time']/60;//分钟
        $data = [
            'sn_value'=>$param['sn'],
            'type'=>$type,
            'app_id'=>$appId,
            'minute'=>$minute
        ];

        $run = DB::table('t_run_app')->where('sn_value',$param['sn'])->first(['id']);
        if($run){
            $data['update_time'] = time();
            $res = DB::table('t_run_app')->where('sn_value',$param['sn'])->update($data);
        }else{
            $data['create_time'] = time();
            $res = DB::table('t_run_app')->insert($data);
        }

        if($res){
            return ToolUtil::returnJson(200,'成功');
        }
        return ToolUtil::returnJson(-200,'失败');
    }

    /**
     * 应用安装或卸载成功后调用
     * @param $param
     * @return false|string
     */
    public static function addAppInstall($param){
        try {
            $parentSn = ParentSnModel::queryLeftAdminSn(['a.value'=>$param['sn']],['p.teacher_id','p.admin_sn_id']);
            if(empty($parentSn)){
                return ToolUtil::returnJson(-200,'该设备还没有进行绑定');
            }
            $app = json_decode($param['app'],true);
            if(!$app){
                return ToolUtil::returnJson(-200,'数据格式不对');
            }
            
            $add = [];
            $add_num = 0;
            if($parentSn['teacher_id']){
                
                $batch = DB::table('t_teacher_sn')->where(['admin_id'=>$parentSn['teacher_id'],'admin_sn_id'=>$parentSn['admin_sn_id']])->value('batch_id');
                $isset = [];
                foreach ($app as $k=>$v){
                    $id = DB::table('t_teacher_app')->whereRaw(" find_in_set('{$batch}',bind_batch_id) ")->where(['app_package'=>$v['app_package']])->first(['id']);
                    if($id){
                        if(!in_array($id['id'],$isset)){
                            $add[$add_num]['id'] = $id['id'];
                            $add[$add_num]['app_type'] = 'teacher_app_id';
                            $add[$add_num]['app_version_code'] = $v['app_version_code'];
                            $add[$add_num]['firstInstallTime'] = $v['firstInstallTime'];
                            $add[$add_num]['lastUpdateTime'] = $v['lastUpdateTime'];
                            $isset[] = $id['id'];
                            $add_num++;
                        }
                    }
                }
                

            }else{
                $isset = [];
                foreach ($app as $k=>$v){
                    $id = ParentAppModel::queryFirst(['sn_value'=>$param['sn'],'app_package'=>$v['app_package']],['id']);
                    if($id){
                        if(!in_array($id['id'],$isset)){
                            $add[$add_num]['id'] = $id['id'];
                            $add[$add_num]['app_type'] = 'parent_app_id';
                            $add[$add_num]['app_version_code'] = $v['app_version_code'];
                            $add[$add_num]['firstInstallTime'] = $v['firstInstallTime'];
                            $add[$add_num]['lastUpdateTime'] = $v['lastUpdateTime'];
                            $isset[] = $id['id'];
                            $add_num++;
                        }
                    }
                }
                
            }
            
            if($add){
                DB::beginTransaction();
                DB::table('t_app_install')->where(['sn_value'=>$param['sn']])->delete();
                foreach ($add as $value){
                    if(DB::table('t_app_install')->where(['sn_value'=>$param['sn'],"$value[app_type]"=>$value['id']])->value('id')){
                        DB::table('t_app_install')->where(['sn_value'=>$param['sn'],"$value[app_type]"=>$value['id']])->update(['update_time'=>time()]);
                    }else{
                        DB::table('t_app_install')->insert(['app_version_code'=>$value['app_version_code'],'firstInstallTime'=>$value['firstInstallTime'],'lastUpdateTime'=>$value['lastUpdateTime'],'sn_value'=>$param['sn'],"$value[app_type]"=>$value['id'],'create_time'=>time()]);
                    }
                }
                DB::commit();
                return ToolUtil::returnJson(200,'成功');
            }
            return ToolUtil::returnJson(-200,'失败');
        }catch (\Exception $exception){
            DB::rollBack();
            return ToolUtil::returnJson(-200,$exception->getMessage());
        }
    }

    /**
     * 推送应用刷新后调用
     * @param $param
     * @return false|string
     */
    public static function updateAppInstall($param){
        $parentSn = ParentSnModel::queryLeftAdminSn(['a.value'=>$param['sn']],['p.teacher_id']);
        if(empty($parentSn)){
            return ToolUtil::returnJson(-200,'该设备还没有进行绑定');
        }
        $info = json_decode($param['info'],true);
        $admin = AdminSnModel::queryFirst(['value'=>$param['sn']],['minute']);
        $time = $param['end_time'] - $param['start_time'];
        $minute = ($admin['minute']+$time)/60;
        AdminSnModel::edit(['value'=>$param['sn']],['quantity'=>$param['electric'],'is_wifi'=>$param['is_wifi'],'minute'=>$minute]);
        AppInstallModel::edit(['sn_value'=>$param['sn']],['status'=>0]);
        if($parentSn['teacher_id']){
            foreach ($info as $k=>$v){
                $teacher = TeacherAppModel::queryFirst(['app_package'=>$v['packageName'],['app_version_code'=>$v['versionCode']]],['id']);
                if(empty($teacher)){
                    $sys = SysAppModel::queryFirst(['app_package'=>$v['packageName']],['id']);
                    AppInstallModel::add(['sn_value'=>$param['sn'],'sys_app_id'=>$sys['id'],'status'=>$v['state'],'minute'=>isset($v['minute'])?$v['minute']:0]);
                }else{
                    AppInstallModel::edit(['sn_value'=>$param['sn'],'teacher_app_id'=>$teacher['id']],
                        ['status'=>$v['state'],'minute'=>isset($v['minute'])?$v['minute']:0]);
                }
            }
            return ToolUtil::returnJson(200,'成功');
        }else{
            foreach ($info as $k=>$v){
                $parent = ParentAppModel::queryFirst(['app_package'=>$v['packageName'],'app_version_code'=>$v['versionCode']],['id']);
                if(empty($parent)){
                    $sys = SysAppModel::queryFirst(['app_package'=>$v['packageName']],['id']);
                    AppInstallModel::add(['sn_value'=>$param['sn'],'sys_app_id'=>$sys['id'],'status'=>$v['state'],'minute'=>isset($v['minute'])?$v['minute']:0]);
                }else{
                    AppInstallModel::edit(['sn_value'=>$param['sn'],'parent_app_id'=>$parent['id']],
                        ['status'=>$v['state'],'minute'=>isset($v['minute'])?$v['minute']:0]);
                }
            }
            return ToolUtil::returnJson(200,'成功');
        }
    }

    /**
     * 应用日志信息
     * @param $param
     * @return false|string
     */
    public static function addAppLog($param){
        $parentSn = ParentSnModel::queryLeftAdminSn(['a.value'=>$param['sn']],['p.teacher_id']);
        if($parentSn){
            if($parentSn['teacher_id']){
                $teacherApp = TeacherAppModel::queryFirst(['app_package'=>$param['packageName'],'app_version_code'=>$param['versionCode']],['id']);
                if(!$teacherApp){
                    return ToolUtil::returnJson(400,'没有这个应用信息1');
                }
                if($param['type']==1){
                    $int = AppLogModel::add(['sn_value'=>$param['sn'],'parent_app_id'=>$teacherApp['id'],'create_time'=>$param['createTime']]);
                }else{
                    $app = AppLogModel::queryFirst(['sn_value'=>$param['sn'],'update_time'=>null],['create_time']);
                    $minute = round(($param['createTime'] - $app['create_time'])/60,0);
                    $int = AppLogModel::edit(['sn_value'=>$param['sn'],'update_time'=>null],['update_time'=>$param['createTime'],'minute'=>$minute]);
                }
            }else{
                $parentApp = ParentAppModel::queryFirst(['app_package'=>$param['packageName'],'app_version_code'=>$param['versionCode']],['id']);
                if(!$parentApp){
                    return ToolUtil::returnJson(400,'没有这个应用信息');
                }
                if($param['type']==1){
                    $int = AppLogModel::add(['sn_value'=>$param['sn'],'parent_app_id'=>$parentApp['id'],'create_time'=>$param['createTime']]);
                }else{
                    $app = AppLogModel::queryFirst(['sn_value'=>$param['sn'],'update_time'=>null],['create_time']);
                    $minute = round(($param['createTime'] - $app['create_time'])/60,0);
                    $int = AppLogModel::edit(['sn_value'=>$param['sn'],'update_time'=>null],['update_time'=>$param['createTime'],'minute'=>$minute]);
                }
            }
            if($int){
                return ToolUtil::returnJson(200,'成功');
            }
            return ToolUtil::returnJson(-200,'失败');
        }
    }

    /**
     * 下载应用完成调用
     * @param $param
     * @return false|string
     */
    public static function downloadApp($param){
        $adminSn = AdminSnModel::queryFirst(['value'=>$param['sn']],['id']);
        if(!$adminSn){
            return ToolUtil::returnJson(400,'不存在该设备');
        }
        $data = [
            'package_name'=>$param['package_name'],
            'app_size'=>$param['app_size'],
            'sn_value'=>$param['sn'],
            'create_time'=>time(),
            'admin_id'=>$param['userId']
        ];
        if(StatisticsAppModel::add($data)){
            return ToolUtil::returnJson(200,'成功');
        }
        return ToolUtil::returnJson(-200,'失败');
    }

    /**
     * sn获取所有应用信息
     * @param $param
     * @return false|string
     */
    public static function queryAllApp($param){
        $where = [];
        if(isset($param['app_name']) && !empty($param['app_name'])){
            $where[count($where)+1] = " a.app_name like '%$param[app_name]%' ";
        }
        $parentSn = ParentSnModel::queryLeftAdminSn(['a.value'=>$param['sn']],['a.is_lock','p.id','teacher_id']);
        if($parentSn){

            if($parentSn['is_lock'] === 0){
                return ToolUtil::returnJson(400,'没有数据');
            }

            $field = "a.app_name,a.app_package,a.app_version_code,a.app_size,a.app_url,a.app_img,a.app_md5,
            a.is_silent";
            if($parentSn['teacher_id']){
                $teacherSn = TeacherSnModel::queryLeftAdminSn(['a.value'=>$param['sn']],['b.id']);
                if($teacherSn){
                    $batch = $teacherSn['id'];
                    $where[count($where)+1] = " find_in_set('{$batch}',a.bind_batch_id) ";
                    $str = ' where '.implode('and',$where);
                    $data = DB::select("select $field from t_teacher_app as a $str");
                }else{
                    $data = [];
                }
            }else{
                $where[count($where)+1] = " a.sn_value='$param[sn]' ";
                $str = ' where '.implode('and',$where);
                $data = DB::select("select $field from t_parent_app as a $str");
            }
            if(count($data)){
                return ToolUtil::returnJson(200,'成功',$data);
            }
            return ToolUtil::returnJson(400,'没有数据');
        }
        return ToolUtil::returnJson(-200,'该设备没有绑定');
    }

    /**
     * 包名和内部版本号获取应用信息
     * @param $param
     * @return false|string
     */
    public static function queryPackageApp($param){
        $field = ['app_name','app_version_name','app_package','app_version_code','app_size','app_url','app_img','is_silent',
            'app_preview1','app_preview2','app_preview3','app_developer'];
        $data = ParentAppModel::queryFirst(['app_package'=>$param['packageName'],'app_version_code'=>$param['versionCode']],$field);
        if($data){
            $data['app_preview1'] = $data['app_preview1']?$data['app_preview1']:'';
            $data['app_preview2'] = $data['app_preview2']?$data['app_preview2']:'';
            $data['app_preview3'] = $data['app_preview3']?$data['app_preview3']:'';
            return ToolUtil::returnJson(200,'成功',$data);
        }else{
            $data = TeacherAppModel::queryFirst(['app_package'=>$param['packageName'],'app_version_code'=>$param['versionCode']],$field);
            if($data){
                $data['app_preview1'] = $data['app_preview1']?$data['app_preview1']:'';
                $data['app_preview2'] = $data['app_preview2']?$data['app_preview2']:'';
                $data['app_preview3'] = $data['app_preview3']?$data['app_preview3']:'';
                return ToolUtil::returnJson(200,'成功',$data);
            }
            return ToolUtil::returnJson(400,'没有数据');
        }
    }

    /**
     * 获取全局更新应用信息
     * @param $param
     * @return false|string
     */
    public static function newestAppUpdate($param){
        $field = ['app_name','app_package','app_version_name','app_version_code','app_size','app_desc','app_md5','app_url','status'];
        $data = AppUpdateModel::queryNewest(['app_package'=>$param['packageName']],$field);
        if($data){

            if($data['status'] === 3){

                if($data['app_version_code'] <= $param['versionCode']){
                    return ToolUtil::returnJson(301,'当前版本相同');
                }
                unset($data['status']);
                return ToolUtil::returnJson(200,'成功',$data);

            }else{

                if(isset($param['type'])){
                    $where = ['app_package'=>$param['packageName'],'status'=>(int)$param['type']];
                }else{
                    $where = ['app_package'=>$param['packageName']];
                }

                $data2 = AppUpdateModel::queryNewest($where,$field);
                if(empty($data2)){
                    return ToolUtil::returnJson(400,'没有数据');
                }
                if($data2['app_version_code'] <= $param['versionCode']){
                    return ToolUtil::returnJson(301,'当前版本相同');
                }
                unset($data2['status']);
                return ToolUtil::returnJson(200,'成功',$data2);

            }
            
        }
        return ToolUtil::returnJson(400,'没有数据');
    }

    /**
     * 获取全局更新包名
     * @return false|string
     */
    public static function queryAppUpdate(){
        $field = ['app_package'];
        $data = AppUpdateModel::queryGet([],$field);
        if(count($data)){
            return ToolUtil::returnJson(200,'成功',$data);
        }
        return ToolUtil::returnJson(400,'没有数据');
    }
}